import NetService from './net.service'
import { ref, reactive } from 'vue'
import { Service, injectable, mutex } from './service'

interface sectionData {
  id: string;
  startPosition: number;
  endPosition: number;
  direction: number
  describe: string
  [index:string]:string | number | boolean
}

@injectable
export default class SectionService extends Service {
  public sections = ref<sectionData[]>([])
  public addData = reactive({
    direction: '',
    endPosition: '',
    startPosition: '',
    id: '',
    describe: ''
  })

  /** 道岔下拉选所需数据 */
  public turnoutsOption = ref([{ value: '', label: '' }])
  private netService = new NetService()
  @mutex
  async load () {
    // 加载全部 区段 数据
    // 判断是否全部加载 如果已经加载 忽略
    if (this.sections.value.length > 0) {
      return
    }
    const res = await this.netService.get('/lsections/list')

    if (res?.success) {
      res?.data.forEach((item: { direction: string | number; id: { toString: (arg0: number) => string };}, index: number) => {
        item.id = item.id.toString(16).replace('"', '').replace('"', '').toUpperCase()
      })
      this.sections.value = res?.data
    }
  }

  async add (params: {
    id: string;
    startPosition: number;
    endPosition: number;
    direction: number;
    describe: string
  }) {
    const res = await this.netService.post('/lsections/insert', params)
    return res
  }

  /** 修改数据及push进数组数据处理 */
  async change (params: {
    id: string;
    startPosition: number;
    endPosition: number;
    direction: number
    describe: string
  }) {
    const res = await this.netService.post('/lsections/update', params)
    if (res?.success) {
      params.id = parseInt(params.id).toString(16).toUpperCase()
      params.endPosition = Number(params.endPosition)
      params.startPosition = Number(params.startPosition)
      const delIndex = this.sections.value.findIndex((e, index) => {
        return e.id === params.id
      })
      this.sections.value.splice(delIndex, 1, params)
    }
    return res
  }

  async del (params: { id: string; }) {
    const res = await this.netService.post('/lsections/delete', params, 'posturl')
    if (res?.success) {
      /** 找到删除行数据id */
      const delIndex = this.sections.value.findIndex((e, index) => {
        return e.id === parseInt(params.id).toString(16).toUpperCase()
      })
      this.sections.value.splice(delIndex, 1)
    }
    return res
  }
}
